package top.lixunda.books3.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.lixunda.books3.model.Message;
import top.lixunda.books3.model.SmsResult;
import top.lixunda.books3.service.VerifyService;
import top.lixunda.books3.util.Log;
import top.lixunda.books3.util.VerifyCode;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class VerifyController {

    @Autowired
    private VerifyService verifyService;

    @RequestMapping(value = "/loginImage", method = RequestMethod.GET)
    public void createLoginImage(HttpServletResponse response){
        VerifyCode.VerifyInfo verifyInfo = verifyService.createLoginVerifyImage();
        try {
            VerifyCode.output(verifyInfo.getBufferedImage(), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/registerImage", method = RequestMethod.GET)
    public void createRegisterImage(HttpServletResponse response){
        VerifyCode.VerifyInfo verifyInfo = verifyService.createRegisterVerifyImage();
        try {
            VerifyCode.output(verifyInfo.getBufferedImage(), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/sendRegisterSms", method = RequestMethod.POST)
    @ResponseBody
    public Message sendRegisterSms(@RequestParam(value = "phone", required = false, defaultValue = "") String phone,
                                   @RequestParam(value = "verify", required = false, defaultValue = "") String verify){
        Log.d("发送注册短信 "+phone+"  "+verify);
        //1. 判断验证码
        if(!verifyService.judgeRegisterVerify(verify)){
            return Message.errorClientVerify();
        }
        //2. 发送短信
        SmsResult result = verifyService.sendRegisterSms(phone);
        if(result == null || !result.getRespCode().equals(SmsResult.RespCodeSuccess)){
            //发送短信失败
            Log.d("向 "+phone+" 发送注册验证码失败");
            return Message.errorServer("发送短信到"+phone+"失败").setData(result == null ? null : result.getRespCode()+"#"+result.getRespDesc());
        }
        return Message.successData("发送短信成功");
    }

}
